// ==UserScript==
// @namespace starconqueror@hotmail.com
// @author Starconqueror based on Pio's infocenter (http://forum.pardus.at/index.php?showtopic=35120)
// @name War mission share
// @include http://orion.pardus.at/bulletin_board.php
// @include http://orion.pardus.at/overview_stats.php
// ==/UserScript==

//
// Get rank
//
if(document.URL.indexOf('overview_stats.php') >= 0) {

  var imgSrc = document.body.getElementsByTagName("table")[0].getElementsByTagName("table")[3].getElementsByTagName("table")[0].getElementsByTagName("table")[0].rows[5].getElementsByTagName("img")[1].src;
  var rank = imgSrc.substring(imgSrc.lastIndexOf("/") + 1, imgSrc.lastIndexOf("."));
  GM_setValue('rank', rank);

}


var universe = "orion"

function saveBoard() {
	var accounts = {
		orion: {name: "FalCLogG3R", password: "1099pWd", server: "http://logger.fedfalcons.com"},
	}

	function extractWord(text, startsWith, endsWith, fromStart) {
		if (fromStart) {
			var i = text.toLowerCase().indexOf(startsWith.toLowerCase());
			var str = text.substr(i + startsWith.length, text.length);
			i = str.toLowerCase().indexOf(endsWith.toLowerCase());
			return str.substr(0, i);
		} else {
			var i = text.toLowerCase().indexOf(endsWith.toLowerCase());
			var str = text.substr(0, i);
			i = str.toLowerCase().lastIndexOf(startsWith.toLowerCase());
			return str.substr(i + startsWith.length, str.length);
		}
	}

	function trim(str) {
		var result = str.replace(/^\s+/, "");
		return result.replace(/\s+$/, "");
	}

	function appendFormElement(form, elemName, type, name, value) {
		var elem = document.createElement(elemName);
		if (type)
			elem.type = type;
		elem.name = name;
		elem.value = value;
		form.appendChild(elem);
	}

	function extractFirstText(node) {
		var NODE_TEXT = 3;
		while (node.nodeType != NODE_TEXT && node.childNodes.length > 0)
			node = node.childNodes[0];
		return node.nodeValue;
	}

	MISSION_SCOUT = "Scout";
        MISSION_TRANSPORT_SPY = "Transport Spy";
        MISSION_ESPIONAGE = "Espionage";
        MISSION_TRANSPORT_MILITARY_EXPLOSIVES = "Transport Military Explosives";
        
	var msgsTable = document.body.getElementsByTagName("table")[2];
	var p = msgsTable.getElementsByTagName("p")[0];
	var source = extractWord(p.innerHTML, "Return to ", "'s", true);

	var tables = msgsTable.getElementsByTagName("table");
	var missions = [];

	var xml = document.implementation.createDocument("", "missions", null);
	var xmlMissions = xml.documentElement;
	var collection = xml.createAttribute("collection");
	collection.value = true;
	xmlMissions.attributes.setNamedItem(collection);

	//Get mission time in GMT
	var missionTime = new Date();
	missionTime.setTime(missionTime.getTime() + missionTime.getTimezoneOffset()*60*1000);
	var when = missionTime.getTime();

	for (var i = 0; i < tables.length; i++) {
		var msgTable = tables[i];
		if (msgTable.getElementsByTagName("table").length == 0)
			continue;

		var mission = {"source": source, "when": when};

		var text = document.location.hostname;
		var account = accounts[universe];
		if (!account)
			return;
		mission.universe = universe.charAt(0).toUpperCase() + universe.substring(1);

		var cell = msgTable.rows[0].cells[0];
		/*var img = cell.getElementsByTagName("img")[0];
		if (img) {
			var factionType = extractWord(img.src, "sign_", "_16x16.png", false);
			if (factionType == "eps" || factionType == "tss")
				cell = msgTable.rows[0].cells[1];
			mission.faction = factionType;
		}*/
		mission.type = trim(cell.textContent);
		var cellCount = msgTable.rows[2].cells.length;
		cell = msgTable.rows[2].cells[cellCount - 1];
		mission.pid = cell.getElementsByTagName("div")[0].id;
		mission.pid = mission.pid.substr(1, mission.pid.length);
		
		if (mission.type.substring(0, 8) == "War Pts:") {
			mission.type = extractWord(msgTable.rows[0].cells[1].textContent, " ", " LONG-TERM", true);
			
			var text = msgTable.rows[1].cells[2].innerHTML;
				
			mission.sector = extractWord(text, "<B>", "</B> at the coordinates");
			mission.coords = extractWord(text, "coordinates [<B>", "</B>", true);
			mission.destination = extractWord(text, "<B>", "</B> in sector");

			mission.reward = extractWord(text, "<B>", "</B> credits").replace(/,/g, "");
			mission.deposit = extractWord(text, "completed: ", " credits", true).replace(/,/g, "");
			mission.timelimit = extractWord(text, "within the next <B>", "</B>", true);
			mission.rank = GM_getValue('rank');
			
			var img = msgTable.rows[0].cells[1].getElementsByTagName("img")[0];			
			if (img) {
				var factionType = extractWord(img.src, "sign_", "_16x16.png", false);
				if (factionType == "eps" || factionType == "tss")
					cell = msgTable.rows[0].cells[1];
				mission.faction = factionType;
			}
			
			if (mission.type == MISSION_ESPIONAGE) {
				var imgSrc = msgTable.rows[2].cells[0].getElementsByTagName("img")[0].src;
				mission.opponent = imgSrc.substring(imgSrc.lastIndexOf("/") + 1, imgSrc.lastIndexOf("."));
			}
			
			missions.push(mission);
			var xmlMission = xml.createElement("mission");
			var j;
			for (j in mission) {
				var prop = xml.createElement(j);
				prop.appendChild(xml.createTextNode(mission[j]));
				xmlMission.appendChild(prop);
			}
			xmlMissions.appendChild(xmlMission);
		}
		
	}

	var form = document.createElement("form");
	form.action = account.server + "/missions_add.php";
	form.method = "post";
	form.target = "missionsAdd";
	form.style.display = "none";
	var data = new XMLSerializer().serializeToString(xml);
	appendFormElement(form, "textarea", null, "missions", data);
	appendFormElement(form, "input", "text", "acc", account.name);
	appendFormElement(form, "input", "text", "pwd", account.password);
	document.body.appendChild(form);
	frame = document.createElement("iframe");
	frame.name = "missionsAdd";
	frame.style.display = "none";
	document.body.appendChild(frame);
	form.submit();
}

if(document.URL.indexOf('bulletin_board.php') >= 0) {
	saveBoard();
}